#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'获取对象信息：当拿到一个对象的引用时，如何知道其类型？'

import types

# 使用type(obj)判断基本数据类型
print(type(123) == int) # True
print(type('123') == str) # True

#
def fn():
    pass
print(type(fn) == types.FunctionType) # True
print(type(fn) == types.LambdaType) # True

print(type(lambda x:x+x) == types.FunctionType) #True
print(type(lambda x:x+x) == types.LambdaType) #True

print(type((x for x in range(10))) == types.GeneratorType) #True

# 判断继承关系：isinstance()
class Animal(object):
    def run(self):
        print(self.__class__.__name__  + ' is running')

class Dog(Animal):
    def eat(self):
        print(self.__class__.__name__ + ' eating bone')

animal = Animal()

dog = Dog()

print(isinstance(dog,Animal)) # True
print(isinstance(dog,Dog)) # True

# dir()
print(dir(str)) # ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(Animal)) # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'run']
# 有x属性吗？
print(hasattr(animal,'x')) # False
print(hasattr(animal,'__class__')) # True
print(hasattr(animal,'run')) # True
# 获取属性
print(getattr(animal,'run')) # <bound method Animal.run of <__main__.Animal object at 0x000001C6655FE198>>
# 设置属性
setattr(animal,'x',20)
print(getattr(animal,'x')) # 20
# 如果属性不存在，则抛出错误

